package cn.b.sky.user;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
public class MyAccessDecisionManager implements AccessDecisionManager {
  
  /**
   * 超级管理员SA拥有所以得权限
   */
  public static final String ALLACCESSDECIDION = "HAS_ALL_ACCESSDECISION";
  /**
   * 检查用户是否够权限访问资源 
   * @authentication 从spring的全局缓存SecurityContextHolder中拿到的，里面存有用户的权限信息 
   * @object 里面包含待访问的url  
   * @configAttributes 所需的权限
   */
  @Override
  public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
      throws AccessDeniedException {
    if (configAttributes == null) {
      return;
    }
    for (ConfigAttribute item : configAttributes) {
      String needAuth = ((SecurityConfig) item).getAttribute();
      for (GrantedAuthority ga : authentication.getAuthorities()) {
        if (needAuth.equals(ga.getAuthority())) {
          return;
        }else if(ALLACCESSDECIDION.equalsIgnoreCase(ga.getAuthority())){
          return;
        }
      }
    }
    throw new AccessDeniedException("There is not enough access to visit!");
  }

  @Override
  public boolean supports(ConfigAttribute attribute) {
    return true;
  }

  @Override
  public boolean supports(Class<?> clazz) {
    return true;
  }
}